/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年6月27日
 */
package com.massyframework.beanskin.util.nativelib;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 动态库工具类。
 * <p>
 * 提供加载和卸载原生代码动态库的封装.
 * @author huangkh
 *
 */
public abstract class NativeLibraryUtils {
	    
    /**
     * 卸载动态库
     * @param classLoader {@link ClassLoader},加载动态库的类加载器
     * @param libPath {@link String},动态库的路经
     */
    @SuppressWarnings({ "unchecked","rawtypes" })
	public static synchronized void unloadLibrary(String libPath, ClassLoader classLoader) {
        try {
            Field field = ClassLoader.class.getDeclaredField("nativeLibraries");
            field.setAccessible(true);
            Vector<Object> libs = (Vector<Object>) field.get(classLoader);
            Iterator it = libs.iterator();
            while (it.hasNext()) {
                Object object = it.next();
                Field[] fs = object.getClass().getDeclaredFields();
                for (int k = 0; k < fs.length; k++) {
                    if (fs[k].getName().equals("name")) {
                        fs[k].setAccessible(true);
                        String dllPath = fs[k].get(object).toString();
                        if (dllPath.endsWith(libPath)) {
                            Method finalize = object.getClass().getDeclaredMethod("finalize");
                            finalize.setAccessible(true);
                            finalize.invoke(object);
                        }
                    }
                }
            }
        }catch(Throwable e) {
        	Logger logger = LoggerFactory.getLogger(NativeLibraryUtils.class);
        	if (logger.isErrorEnabled()) {
        		logger.error(e.getMessage(), e);
        	}
        }
    }
    

}
